package com.mori.encrypt.spring.boot.autoconfigure;

import com.mori.encrypt.spring.boot.core.filter.EncryptionFilter;
import com.mori.encrypt.spring.boot.core.init.EncryptDataInit;
import com.mori.encrypt.spring.boot.core.properties.EncryptConfigProperties;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>  </p>
 *
 * @author mori
 * @since 2020/9/29 15:15
 */
@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties(EncryptConfigProperties.class)
public class EncryptAutoConfiguration {

	private EncryptConfigProperties encryptConfig;

	public EncryptAutoConfiguration(EncryptConfigProperties encryptConfig) {
		this.encryptConfig = encryptConfig;
	}

	/**
	 * 注册加密解密过滤器
	 *
	 * @return 过滤器
	 */
	@Bean
	public FilterRegistrationBean<EncryptionFilter> filterRegistration(EncryptDataInit encryptDataInit) {
		FilterRegistrationBean<EncryptionFilter> registration = new FilterRegistrationBean<>();
		List<String> requestDecryptUriList = Stream.of(encryptConfig.getRequestDecryptUriList(),
				encryptDataInit.getRequestDecryptUriList()).flatMap(Collection::stream).collect(Collectors.toList());
		// 设置请求解密uri列表
		encryptConfig.setRequestDecryptUriList(requestDecryptUriList);
		List<String> responseEncryptUriList = Stream.of(encryptConfig.getResponseEncryptUriList(),
				encryptDataInit.getResponseEncryptUriList()).flatMap(Collection::stream).collect(Collectors.toList());
		// 设置响应加密uri列表
		encryptConfig.setResponseEncryptUriList(responseEncryptUriList);
		// 设置请求解密参数map
		encryptConfig.setRequestDecryptParamMap(encryptDataInit.getRequestDecryptParamMap());
		registration.setFilter(new EncryptionFilter(encryptConfig));
		registration.addUrlPatterns(encryptConfig.getUrlPatterns());
		registration.setName("EncryptionFilter");
		registration.setOrder(encryptConfig.getOrder());
		return registration;
	}

	@Bean
	public EncryptDataInit encryptDataInit() {
		return new EncryptDataInit();
	}
}
